package com.yidu.oracle.Tools;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
	static String DRIVER_CLASS;
	static String DRIVER_URL;
	static String DB_NAME;
	static String DB_PASS;

	//使用静态块
	static {
		//io流
		InputStream inputStream=DBUtil.class.getClassLoader().getResourceAsStream("dbconn.properties");
		//Properties数组
		Properties pro=new Properties();
		//读取文件
		try {
			pro.load(inputStream);
			//得到值并赋值
			DRIVER_CLASS=pro.getProperty("conn.driverclass");
			System.out.println(DRIVER_CLASS);
			DRIVER_URL=pro.getProperty("conn.url");
			DB_NAME=pro.getProperty("conn.username");
			DB_PASS=pro.getProperty("conn.userpass");
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//关闭io流
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 返回连接对象
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getConnection() throws ClassNotFoundException, SQLException{
		Class.forName(DRIVER_CLASS);
		return DriverManager.getConnection(DRIVER_URL, DB_NAME, DB_PASS);
	}

	public static void closeSource(Connection connection ,Statement statement , ResultSet resultSet){
		if(null != connection){
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(null != statement){
			try {
				statement.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(null != resultSet){
			try {
				resultSet.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
